package com.lzj.server.utils;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import com.lzj.server.common.model.Log;
import com.lzj.server.constant.enums.LogTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

@Slf4j
public class LogUtils {
    // 日志队列名称
    private static final String LOG_QUEUE_NAME = "log:behavior:queue";

    private static RedissonClient redissonClient;

    // 初始化 Redisson 客户端
    public static void init(RedissonClient client) {
        redissonClient = client;
    }

    /**
     * 推送日志到 Redisson 延迟队列（0秒延迟即异步）
     */
    public static void sendLog(Long userId, String logType, String content, Long objId) {
        try {
            Log log = new Log();
            log.setId(IdUtil.getSnowflakeNextId()); // 可选
            log.setLogType(logType);
            log.setUserId(userId);
            log.setContent(content);
            log.setObjId(objId);
            log.setCreateTime(LocalDateTime.now());

            RBlockingQueue<Log> blockingQueue = redissonClient.getBlockingQueue(LOG_QUEUE_NAME);
            RDelayedQueue<Log> delayedQueue = redissonClient.getDelayedQueue(blockingQueue);
            delayedQueue.offer(log, 0, TimeUnit.SECONDS); // 立即投递（异步）
        } catch (Exception e) {
            log.error("日志队列投递失败", e);
        }
    }

    /**
     * 队列消费器调用：阻塞消费日志
     */
    public static RBlockingQueue<Log> getLogQueue() {
        return redissonClient.getBlockingQueue(LOG_QUEUE_NAME);
    }

    public void recordViewLog(Long objId) {
        sendLog(StpUtil.getLoginIdAsLong(), LogTypeEnum.VIEW.getCode(), StpUtil.getLoginIdAsLong() + "," + objId, objId);
    }

    public void recordCommentLog(Long objId) {
        sendLog(StpUtil.getLoginIdAsLong(), LogTypeEnum.COMMENT.getCode(), StpUtil.getLoginIdAsLong() + "," + objId, objId);
    }

    public void recordLikeLog(Long objId) {
        sendLog(StpUtil.getLoginIdAsLong(), LogTypeEnum.LIKE.getCode(), StpUtil.getLoginIdAsLong() + "," + objId, objId);

    }

    public void recordCollectLog(Long objId) {
        sendLog(StpUtil.getLoginIdAsLong(), LogTypeEnum.COLLECT.getCode(), StpUtil.getLoginIdAsLong() + "," + objId, objId);
    }

    public void recordDownloadLog(Long objId) {
        sendLog(StpUtil.getLoginIdAsLong(), LogTypeEnum.DOWNLOAD.getCode(), StpUtil.getLoginIdAsLong() + "," + objId, objId);
    }
}
